{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length of the dataset:1115394\n",
      "First Citizen:\n",
      "Before we proceed any further, hear\n"
     ]
    }
   ],
   "source": [
    "with open(\"../dataset.txt\", \"r\", encoding=\"utf-8\") as f:\n",
    "    rawdata = f.read()\n",
    "rawdata_len = len(rawdata)\n",
    "# —————————————————————————————————————————————————————— #\n",
    "print(f\"Length of the dataset:{rawdata_len}\")\n",
    "print(rawdata[:50])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们将每个字符作为token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "There are 65 tokens\n",
      "\n",
      " !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n"
     ]
    }
   ],
   "source": [
    "tokens = sorted(list(set(rawdata)))\n",
    "tokens_len = len(tokens)\n",
    "# —————————————————————————————————————————————————————— #\n",
    "print(f\"There are {tokens_len} tokens\")\n",
    "print(\"\".join(tokens))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对token进行索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[20, 43, 50, 50, 53]\n",
      "Hello\n"
     ]
    }
   ],
   "source": [
    "ctoi = {ch:idx for idx, ch in enumerate(tokens)}\n",
    "itoc = tokens\n",
    "encode = lambda string: [ctoi[c] for c in string]\n",
    "decode = lambda idxs: \"\".join([itoc[idx] for idx in idxs])\n",
    "# —————————————————————————————————————————————————————— #\n",
    "print(encode(\"Hello\"))\n",
    "print(decode(encode(\"Hello\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将整个文本进行编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([18, 47, 56, 57, 58,  1, 15, 47, 58, 47, 64, 43, 52, 10,  0, 14, 43, 44,\n",
      "        53, 56, 43,  1, 61, 43,  1, 54, 56, 53, 41, 43, 43, 42,  1, 39, 52, 63,\n",
      "         1, 44, 59, 56, 58, 46, 43, 56,  6,  1, 46, 43, 39, 56])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "data = torch.tensor(encode(rawdata), dtype=torch.long)\n",
    "# —————————————————————————————————————————————————————— #\n",
    "print(data[:50])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "按照90%分为训练集和验证集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = data[:int(rawdata_len*0.9)]\n",
    "test_data = data[int(rawdata_len*0.9):]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将随机数据分批训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(tensor([[53, 59,  6,  1, 58, 56, 47, 40],\n",
      "        [49, 43, 43, 54,  1, 47, 58,  1],\n",
      "        [13, 52, 45, 43, 50, 53,  8,  0],\n",
      "        [ 1, 39,  1, 46, 53, 59, 57, 43]]), tensor([[59,  6,  1, 58, 56, 47, 40, 59],\n",
      "        [43, 43, 54,  1, 47, 58,  1, 58],\n",
      "        [52, 45, 43, 50, 53,  8,  0, 26],\n",
      "        [39,  1, 46, 53, 59, 57, 43,  0]]))\n"
     ]
    }
   ],
   "source": [
    "torch.manual_seed(1337)\n",
    "batch_size = 32\n",
    "block_size = 8\n",
    "\n",
    "def get_batch(mode=\"train\"):\n",
    "    indata, indata_len = (train_data, int(rawdata_len*0.9)) if mode==\"train\"\\\n",
    "          else (test_data, rawdata_len - int(rawdata_len*0.9))\n",
    "    idxs = torch.randint(0, indata_len-1-block_size, (batch_size,))\n",
    "    x = torch.stack([indata[idx:idx+block_size] for idx in idxs])\n",
    "    y = torch.stack([indata[idx+1:idx+block_size+1] for idx in idxs])\n",
    "    return x, y\n",
    "# —————————————————————————————————————————————————————— #\n",
    "print(get_batch())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最简单的BiGram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "S3fh$-M$gCjxvbRj;pGGju;TgCjXOca!CVtTbV$JSV;xZ$Q!U-\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Administrator\\anaconda3\\envs\\python3.7.2\\lib\\site-packages\\ipykernel_launcher.py:30: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n"
     ]
    }
   ],
   "source": [
    "import torch.nn as nn\n",
    "torch.manual_seed(1337)\n",
    "class BiGramModule(nn.Module):\n",
    "    def __init__(self, vocab_size) -> None:\n",
    "        super().__init__()\n",
    "        self.vocab_to_prob_table = nn.Embedding(vocab_size, vocab_size)\n",
    "\n",
    "    def forward(self, X, Targets=None):\n",
    "        # X's shape is (B, T)\n",
    "        # X's shape is (B, T)\n",
    "        logits = self.vocab_to_prob_table(X)\n",
    "        # logits's shape is (B, T, C).C: Channels in CNN is different color channels,\n",
    "        #  here is different meaning of a token(dims of embedding)\n",
    "        if Targets is not None:\n",
    "            B, T, C = logits.shape\n",
    "            logits = logits.view(B*T, C)\n",
    "            Targets = Targets.view(B*T)\n",
    "            loss = torch.nn.functional.cross_entropy(logits, Targets)\n",
    "            return logits, loss\n",
    "        return logits\n",
    "    \n",
    "    def generator(self, idx, new_tokens_len):\n",
    "        # 生成时只有一个批次\n",
    "        # 把所有的idx收集起来是因为后面有根据前面多个预测的模型\n",
    "        for _ in range(new_tokens_len):\n",
    "            logits = self.forward(idx)\n",
    "            logits = logits[:, -1]\n",
    "            # print(logits.shape)\n",
    "            # 取最后一个因为是二元模型\n",
    "            probs = nn.functional.softmax(logits)\n",
    "            idx_next = torch.multinomial(probs, 1, True)\n",
    "            idx = torch.cat((idx, idx_next), dim=1)\n",
    "        return idx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = BiGramModule(tokens_len)\n",
    "print(decode(m.generator(torch.zeros((1, 1), dtype=torch.long), 50)[0].tolist()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.416433811187744\n"
     ]
    }
   ],
   "source": [
    "lr = 1e-3\n",
    "optim = torch.optim.AdamW(m.parameters(), lr)\n",
    "for _ in range(10000):\n",
    "    x, y = get_batch()\n",
    "    logits, loss = m.forward(x, y)\n",
    "    optim.zero_grad()\n",
    "    loss.backward()\n",
    "    optim.step()\n",
    "print(loss.item())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再次预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Itrg rw y y heren;\n",
      "Wies I mut wnd thayendistlo-musplll CENo blawean; is\n",
      "Wesin stontherdshind I who!\n",
      "CKI'l'do be RI athived,\n",
      "Thely; rs w'lart comabe if\n",
      "\n",
      "Me a llouel,\n",
      "R antemindeasst cknofomas, thetenthe le-g, ghe t Gothabiblite s nd.\n",
      "YConio thy ser'd D llle s, thofrotofldo:\n",
      "thrr wroundof\n",
      "I thast ce i\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Administrator\\anaconda3\\envs\\python3.7.2\\lib\\site-packages\\ipykernel_launcher.py:30: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n"
     ]
    }
   ],
   "source": [
    "print(decode(m.generator(torch.zeros((1, 1), dtype=torch.long), 300)[0].tolist()))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3.7.2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
